<template>
    <div  class="m-drawer">
        <el-drawer
      v-model="visible"
      :title="title"
      :size="size"
      :direction="direction"
      :with-header="withHeader"
      :before-close="handleClose"
      :destroy-on-close="destroyOnClose"
      :custom-class="customClass"
      :append-to-body="appendToBody"
      :modal-append-to-body="modalAppendToBody"
      :wrapper-closable="wrapperClosable"
      :modal="modal"
      :show-close="showClose"
     
    >
      <!-- 自定义header -->
      <template v-if="withHeader && $slots.header" #header>
        <slot name="header"></slot>
      </template>
      
      <!-- 自定义title -->
      <template v-if="withHeader && $slots.title" #title>
        <slot name="title"></slot>
      </template>
      
      <!-- 默认内容 -->
      <div class="m-drawer__content">      
        <slot name="content"></slot>
      </div>
      
      <!-- 底部按钮 -->
      <template v-if="$slots.footer" #footer>
        <slot name="footer"></slot>
      </template>
    </el-drawer>
    </div>

  </template>
  
  <script lang="ts">
  import { defineComponent } from 'vue'
  export default defineComponent({
    name: 'MDrawer',
  })
  </script>
  
  <script setup lang="ts">
  import { ref, watch } from 'vue'
  const modelValue = defineModel<boolean>('modelValue', { required: true })
  const props = defineProps({
    title: {
      type: String,
      default: ''
    },
    size: {
      type: [String, Number],
      default: '30%'
    },
    direction: {
      type: String,
      default: 'rtl',
      validator: (val: string) => ['ltr', 'rtl', 'ttb', 'btt'].includes(val)
    },
    withHeader: {
      type: Boolean,
      default: true
    },
    destroyOnClose: {
      type: Boolean,
      default: false
    },
    customClass: {
      type: String,
      default: ''
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    modalAppendToBody: {
      type: Boolean,
      default: true
    },
    wrapperClosable: {
      type: Boolean,
      default: true
    },
    modal: {
      type: Boolean,
      default: true
    },
    showClose: {
      type: Boolean,
      default: true
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'open', 'opened', 'close', 'closed'])
  // 控制抽屉显示隐藏
  const visible = ref(modelValue.value)
  // 监听父组件传入的modelValue变化
  watch(() => modelValue.value, (val) => {
    visible.value = val
  })
  // 监听本地visible变化，通知父组件更新
  watch(() => visible.value, (val) => {
    emit('update:modelValue', val)
    if (val) {
      emit('open')
    } else {
      emit('close')
    }
  })
  // 关闭前回调
  const handleClose = (done: () => void) => {
    emit('close')
    done()
  }
  </script>
  
  <style lang="scss" scoped>
  @import "@/styles/drawer.scss";
  </style>
 